package com.ijava.base.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ijava.base.domain.Model;
import com.ijava.base.domain.User;
import com.ijava.base.service.ModelService;
import com.ijava.util.DTreeBean;
import com.ijava.util.SystemConfig;

@Controller
@RequestMapping("/admin/model.do")
@SessionAttributes("list")
public class ModelController {
	private static final Logger logger = LoggerFactory.getLogger(ModelController.class);
	@Autowired
	private ModelService service;
	
	@RequestMapping(params = "action=tree")
	public String tree(ModelMap modelMap, HttpSession session)
			throws Exception {
		try {
			String modelId = SystemConfig.getProperty("MODEL.ID");
			Model model = service.get(modelId);
			if(null == model){
				User loginUser = (User)session.getAttribute("loginUser");
				String modelParentId = SystemConfig.getProperty("MODEL.PID");
				String modelCode = SystemConfig.getProperty("MODEL.CODE");
				String modelName = SystemConfig.getProperty("MODEL.NAME");
				model = new Model(modelParentId,modelCode,modelName,null);
				model.setModelId(modelId);
				model.setModelIsLeaf(0);
				model.setModelLevel(1);
				model.setRowEnable(1);
				model.setCrTime(new Date(System.currentTimeMillis()));
				model.setCrUserId(loginUser.getUserId());
				service.persist(model);
			}
			modelMap.addAttribute("modelId", model.getModelId());
			
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/model/modelIndex.jsp";
	}
	
	@RequestMapping(params = "action=subTree")
	public String subTree(ModelMap modelMap, Model model, HttpSession session,HttpServletRequest request)
			throws Exception {
		try {
			String context = request.getContextPath(); //session.getServletContext().getContextPath();
			List tree = new ArrayList();
			
			List dTreeList = new ArrayList();
			Model topModel = service.get(model.getModelId());
			dTreeList.add(new DTreeBean(topModel.getModelId(),topModel.getModelParentId(), topModel.getModelName(),
					context+"/admin/model.do?action=list&modelLevel="+topModel.getModelLevel()+"&modelId="+topModel.getModelId(),
					topModel.getModelName(),"treeListFrame"));
			
			List list = service.findTree(model.getModelId(),tree);
			for (int i = 0; i < list.size(); i++) {
				
//				<c:url value="/admin/model.do?action=list&modelId=${dTree.id}"/>
				Model e = (Model)list.get(i);
				DTreeBean dTree = new DTreeBean(e.getModelId(),
						e.getModelParentId(),
						e.getModelName(),
						context+"/admin/model.do?action=list&modelLevel="+e.getModelLevel()+"&modelId="+e.getModelId(),
						e.getModelName(),"treeListFrame");
				dTreeList.add(dTree);
			}
			modelMap.addAttribute("list", dTreeList);
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/model/modelLeft.jsp";
	}

	@RequestMapping(params = "action=list")
	public String list(ModelMap modelMap, Model model, HttpSession session)
			throws Exception {
		try {
			List list = service.findWithPaging(model);
			modelMap.addAttribute("list", list);
			modelMap.addAttribute("command",model );
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		return "forward:/admin/model/modelList.jsp";
	}
	
	@RequestMapping(params = "action=ajaxRemove")
	public void ajaxRemove(ModelMap modelMap, String modelId, HttpSession session,HttpServletResponse response)
			throws Exception {
		String res = "false";
		try {
			List list = service.findChild(new Model(modelId));
			if(list.size() == 0){
				// has child node
				if(!"_".equals(modelId)){
					service.removeProcess(service.get(modelId));
				}
			}else{
				res = "true";
			}
		} catch (Exception e) {
			logger.error("", e);
//			throw e;
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(res);
	}
	
	
	@RequestMapping(params = "action=saveEdit")
	public String saveEdit(ModelMap modelMap, Model model, HttpSession session)
			throws Exception {
		modelMap.addAttribute("code", "model.modify.success");
		try {
			User loginUser = (User) session.getAttribute("loginUser");
			service.saveAll(model, loginUser);
		} catch (Exception e) {
			modelMap.addAttribute("code", "model.modify.failed");
			modelMap.addAttribute("isError", "true");
			logger.error("", e);
//			throw e;
		}
		return list(modelMap, model, session);
	}
}

